<?php
/**
 * 	app后台财务日志
 *  =============================
 * 	后台父类
 * 	=============================
 *	Author: 李宏宇
 *  Date: 2017-10-10
 * @author Administrator
 *
 */
namespace app\admin\controller;
use Think\Db;
require_once (APP_PATH .'api/FinanceApi.php');
class Finance extends AdminBase{
    //空操作
    public function _empty(){
        header("HTTP/1.0 404 Not Found");
        $this->display('Public:404');
    }
    //财务日志
	public function index(){
		$type = input('type_id');//类型
		$point  = input('date');//年月
		$point_date = strtotime($point);//获取接受到的时间戳
		$data_add_time = strtotime("2017-10");//获取2017年10月的时间戳
		if(!empty($point)){
			if($point_date<$data_add_time){
				$point  = "2017-10";
			}
		}
		
		$times[] = input('start');//开始时间
		$times[] = input('end');//结束时间
		$email = input('email');//手机号
		$member_id = input('member_id');//用户id
		$finance = new \FinanceApi();
// 		if($point){
// 			//获得时间点需要使用的数据表
// 			$finance_month_name = $finance->formatDate($point);
// 		}else{
// 			if(input('start') && input('end')){
// 				//获得时间段需要使用的数据表
// 				$finance_month_name = $finance->formatDate($times);
// 				//时间段where查询条件
// 				$where['add_time'] = array('between',$times);
// 			}else{
// 				//获得当前月份需要调用的数据表
// 				$finance_month_name = $finance->judgeNowMonthFinance();
// 			}
// 		}
		if(!empty($type)){
			$where['finance_type']=$type;
		}
		if(!empty($email)){
			$uid=M('Users')->where("loginName like '%{$email}%'")->find();
			$where['member_id']=$uid['userId'];
		}
        if(!empty($member_id)){
            $where['member_id']=$member_id;
        }
		//筛选
		
        	$list = Db::name('App_finance')->where($where)->order('finance_id desc')->paginate(20,false,['query'=>input()]);
        	$page = $list->render ();
        	$list = $list->all();
        
        
        
        $type=M('App_finance_type')->select();
        $this->assign('type',$type);
       // $list = M('App_finance')->where($where)->order('add_time desc')->paginate(15,false,['query'=>['type_id'=>$type_id],['member_id'=>$member_id]]);
        
		foreach ($list as $k=>$v){
			$user = M('Users')->where(array('userId'=>$list[$k]['member_id']))->find();
			$list[$k]['name'] = $user['loginName'];
			
			$type_name = M('app_finance_type')->where(array('id'=>$list[$k]['finance_type']))->find();
			$list[$k]['type_name'] = $type_name['name'];
			
			$currency = M('app_account_type')->where(['id'=>$v['account_type']])->find();
			$list[$k]['currency_name'] = $currency['name'];
			if($list[$k]['money_type'] == 1){
				$pre = '+';
			}else{
				$pre = '-';
			}
			$list[$k]['money'] = $pre.$list[$k]['money'];
		}
		$this->assign('end_time',time());
		$this->assign('empty','暂未查询到数据');
		$this->assign('list',$list);
		$this->assign('page',$page);
        return $this->fetch();
     }
     
     
     
    //财务明细
    public function count(){
    	$pay=$this->getFinenceByType(array('6'),1);
    	$this->assign('pay',$pay);
    	$pay_admin=$this->getFinenceByType(array('3','13'),0);
    	$this->assign('pay_admin',$pay_admin);
    	$draw=$this->getFinenceByType(array('23'),1);
    	$this->assign('draw',$draw);
    	//统计人民币总额
    	$rmb_count=M('Member')->sum('rmb');
    	$forzen_rmb_count=M('Member')->sum('forzen_rmb');
    	$rmb=$rmb_count+$forzen_rmb_count;
    	$this->assign('rmb',$rmb);
    	//分币种统计
    	$currency=M('Currency')->field('currency_id,currency_name')->select();
    	foreach ($currency as $k=>$v){
    		$currency_user[$k]['num']=M('Currency_user')->where('currency_id='.$v['currency_id'])->sum('num');
    		$currency_user[$k]['forzen_num']=M('Currency_user')->where('currency_id='.$v['currency_id'])->sum('forzen_num');
    		$currency_user[$k]['name']=$v['currency_name'];
    	}
		
    	$this->assign('currency_user',$currency_user);
    	return $this->fetch();
    }
    
    
    private function getFinenceByType($type,$currency=1){
		if($currency==0){
			$where['currency_id']=0;
		}
    	$where['type']=array('in',$type);
    	$rs=M('K_finance')->where($where)->sum('money');
    	return $rs;
    }
    /**
     * 导出excel文件
     */
    public function derivedExcel(){
    	//时间筛选
    	$add_time=I('get.add_time');
    	$end_time=I('get.end_time');
    	$add_time=empty($add_time)?0:strtotime($add_time);
    	$end_time=empty($end_time)?0:strtotime($end_time);
    	$where['add_time'] = array('between',array($add_time,$end_time));
    	$list= M('K_finance')->field("member_id,type,content,money,add_time,currency_id,ip")->order('add_time desc')->where($where)->select();
		
    	foreach ($list as $k=>$v){
    		if($v['currency_id']==1){
				$list[$k]['currency_id']='激活积分';
			}
			if($v['currency_id']==2){
				$list[$k]['currency_id'] = '交易积分';
			}
			if($v['currency_id']==3){
				$list[$k]['currency_id'] = '艺宝积分';
			}
			if($v['currency_id']==2){
				$list[$k]['currency_id'] = '艺尊指数';
			}
    		
    		$list[$k]['add_time']=date('Y-m-d H:i:s',$list[$k]['add_time']);
    	}
    	$title = array(
    			'会员ID',
    			'日志类型',
    			'日志内容',
    			'金额',
    			'操作时间',
    			'操作币种',
    			'操作IP',
    	);
    	$filename= $this->config['name']."财务日志-".date('Y-m-d',time());
    	$r = exportexcel($list,$title,$filename);
    }
	
	/**
	*会员转账记录TODO
	*/
    public function trans(){
		$account=I('account');
		$get['account'] = $account;
		if(!empty($account)){
			$uid = Db::name('Users')->where(['account'=>$account])->find();
			$where['member_id']=$uid['userId'];
		}
		$list = Db::name('App_transfer')->where($where)->order('add_time desc')->paginate(20,false,['query'=>input()]);
		$page = $list->render ();
		$list = $list->all();
		foreach ($list as $k=>$v){
			$user = Db::name('Users')->where(array('userId'=>$v['member_id']))->find();
			$list[$k]['send'] = $user['loginName'];
			$recive_user = Db::name('Users')->where(array('userId'=>$v['receive_id']))->find();
			$list[$k]['receive'] = $recive_user['loginName'];
// 			$list[$k]['type'] = '激活积分';
		}
		$this->assign('get',$get);
		$this->assign('page',$page);
// 		$this->assign('end_time',time());
		$this->assign('empty','暂未查询到数据');
		$this->assign('list',$list);
        return $this->fetch();
	}
	
	public function trans_excel(){
		//时间筛选
    	$add_time=I('get.add_time');
    	$end_time=I('get.end_time');
    	if($add_time=='1970-01-01 08:00:00'){
    		$add_time="";
    	}
    	if($end_time=='1970-01-01 08:00:00'){
    		$end_time="";
    	}
    
    	$add_time = !empty($add_time)?strtotime(I('add_time')):0;
    	$end_time = !empty($end_time)?strtotime(I('end_time')):time();
		
    	$where['add_time'] = array('between',array($add_time,$end_time));
    	$list = M('Transfer')->field('id,member_id,money,content,add_time')->where($where)->order('add_time desc')->select();
    	$title = array(
    			'编号',
    			'用户账号',
    			'转账金额',
    			'转账内容',
    			'转账时间',
    			
    	);
    	$filename= $this->config['name']."会员注册积分转账记录-".date('Y-m-d',time());
    	$r = exportexcel($list,$title,$filename);
	}
	//充值记录
	public function chongzhi(){
		
		$count = M('chongzhi')->count();
        $Page = new Page ( $count, 20 ); // 实例化分页类 传入总记录数和每页显示的记录数(25)        
        $show = $Page->show (); // 分页显示输出
		$list = M('chongzhi')->Field("yang_chongzhi.id,yang_member.account,yang_chongzhi.num,yang_chongzhi.add_time,yang_chongzhi.type,yang_chongzhi.status")->join('yang_member on yang_chongzhi.member_id = yang_member.member_id')->order('yang_chongzhi.id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('page',$show);
		$this->assign('list',$list);
    	return $this->fetch();
    }
    
    
    public function shenhe(){
   		$chongzhi = M('chongzhi')->where(array('id'=>$_POST['cid']))->find();
    	M('chongzhi')->where(array('id'=>$_POST['cid']))->setField('status',$_POST['status']);
    	if($_POST['status']==1){
    		$type = M('account_type')->where(array('chongzhi'=>1))->find();
    		if($type['id']==1){
    			M('member_account')->where(array('member_id'=>$chongzhi['member_id']))->setInc('account_type_1',$chongzhi['num']);
    		}
    		if($type['id']==2){
    			M('member_account')->where(array('member_id'=>$chongzhi['member_id']))->setInc('account_type_2',$chongzhi['num']);
    		}
    		if($type['id']==3){
    			M('member_account')->where(array('member_id'=>$chongzhi['member_id']))->setInc('account_type_3',$chongzhi['num']);
    		}
    		if($type['id']==4){
    			M('member_account')->where(array('member_id'=>$chongzhi['member_id']))->setInc('account_type_4',$chongzhi['num']);
    		}
    		if($type['id']==5){
    			M('member_account')->where(array('member_id'=>$chongzhi['member_id']))->setInc('account_type_5',$chongzhi['num']);
    		}
    	}
    	echo 'success';
    }
    
    public function tixian(){
    	$count = M('withdraw')->count();
        $Page = new Page ( $count,20); // 实例化分页类 传入总记录数和每页显示的记录数(25)        
        $show = $Page->show (); // 分页显示输出
		$list = M('withdraw')->Field("yang_withdraw.id,yang_withdraw.fee,yang_withdraw.cnt,yang_member.account,yang_withdraw.num,yang_withdraw.add_time,yang_withdraw.type,yang_withdraw.status")->join('yang_member on yang_withdraw.member_id = yang_member.member_id')->order('yang_withdraw.id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('page',$show);
		$this->assign('list',$list);
    	return $this->fetch();
    }
    
    public function tshenhe(){
    	$tixian = M('withdraw')->where(array('id'=>$_POST['cid']))->find();
    	M('withdraw')->where(array('id'=>$_POST['cid']))->setField('status',$_POST['status']);
    	if($_POST['status']==-1){
    		$account = M('member_account')->where(array('member_id'=>$tixian['member_id']))->find();
    		$data['id'] = $account['id'];
    		$data['member_id'] = $tixian['member_id'];
    		switch($tixian['cnt']){
    			case 1:
    				$data['account_type_1'] = $account['account_type_1'] + $tixian['num'] + $tixian['fee'];
    				break;
    			case 2:
    				$data['account_type_2'] = $account['account_type_2'] + $tixian['num'] + $tixian['fee'];
    				break;
    			case 3:
    				$data['account_type_3'] = $account['account_type_3'] + $tixian['num'] + $tixian['fee'];
    				break;
    			case 4:
    				$data['account_type_4'] = $account['account_type_4'] + $tixian['num'] + $tixian['fee'];
    				break;
    			case 5:
    				$data['account_type_5'] = $account['account_type_5'] + $tixian['num'] + $tixian['fee'];
    				break;
    		}
    		M('member_account')->save($data);
    	}
    	echo 'success';
    }
    /**
     * 日志类型管理
     */
    public function type(){
    	$list = Db::name('App_finance_type')->select();
    	$this->assign('list',$list);
    	return $this->fetch();
    }
    /**
     * 日志类型详情
     */
    public function details(){
    	$id = input('id');
    	$list = Db::name('App_finance_type')->where(array('id'=>$id))->find();
    	$this->assign('list',$list);
    	return $this->fetch();
    }
    /**
     * 修改
     */
    public function update(){
		$id = input('id');
	
    	$data['type'] = input('name');//文章类型
    	$data['top'] = input('status');//是否在首页显示
    	if($_FILES["pic"]["tmp_name"]){
    		$file = request()->file('pic');
    		$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
    		$data['pic'] = '/public/uploads/' . str_replace('\\', '/', $info->getsaveName ());
    	}
    	$res = Db::name('App_finance_type')->where(array('id'=>$id))->update($data);
    	if($res){
    		$this->success('操作成功');
    	}else{
    		$this->error('操作失败');
    	}
    }
    /**
     * 开关功能
     */
    public function updateStatus(){
    	$id = input('id');
    
    	$list = Db::name('App_finance_type')->where(array('id'=>$id))->find();
    	if($list['status'] == 1){
    		$data['status'] = 0;
    	}else{
    		$data['status'] = 1;
    	}
    	$res = Db::name('App_finance_type')->where(array('id'=>$id))->update($data);
    	if($res){
    		$this->success('修改成功');
    	}else{
    		$this->error('修改失败');
    	}
    }
    /**
     * 波比率
     * @return Ambigous <\think\mixed, string>
     */
    public function bobi(){
    	//今天时间戳 0点-24点
    	$today_time = $this->toDayTime();
    	$today_riqi = date('Y-m-d',$today_time[0]);
    	
    	//昨天时间长 0点-24点
    	$yesterday[] = $today_time[0]-86400;
    	$yesterday[] = $today_time[0];
    	//昨天日期
    	$yester_riqi = date('Y-m-d',$yesterday[0]);
    	//昨日数据
    	$yester_list = Db::name('App_statistics')->where(array('time'=>$yester_riqi))->find();
    	//如果数据表里面没有进行统计
    	if(empty($yester_list)){
    		//查询日期的统计数据
    		$yester_list = $this->getImformation($yesterday);
    		//其他天统计之后加入数据库
    		$res[] = Db::name('App_statistics')->insert($yester_list);
    	}
    	//查询日期的统计数据
    	$now_list = $this->getImformation($today_time);
    	
    	$sql_now_list = Db::name('App_statistics')->where(array('time'=>$today_riqi))->find();
    	if(!empty($sql_now_list)){
    		$res[] = Db::name('App_statistics')->where(array('time'=>$today_riqi))->save($now_list);
    	}else{
    		$res[] = Db::name('App_statistics')->insert($now_list);
    	}
    	$list = Db::name('App_statistics')->order('id desc')->select();
    	
    	$this->assign('list',$list);
    	return $this->fetch();
    	
    	
    	
//     	$date = I('date');
//     	//是否传值了
//     	if($date){
//     		$arr = explode('-',$date);
//     		$date = $arr[2].'-'.$arr[1].'-'.$arr[0];
//     		$start = strtotime($date);
//     		$time[] = $start;
//     		$time[] = $start+86400;
//     	}else{
//     		$time = $this->toDayTime();
//     	}
//     	//判断Statistics表当中有没有数据
//     	$riqi = date('Y-m-d',$time[0]);
//     	//查询日期的数据表里面的数据
//     	$list = $list = Db::name('App_statistics')->where(array('time'=>$riqi))->find();
//     	//如果数据表里面没有进行统计
//     	if(!$list){
//     		//查询日期的统计数据
//     		$list = $this->getImformation($time);
//     		//今天
//     		$now_riqi = date('Y-m-d',time());
//     		//判断是不是今天(不是今天的话统计数据加入数据库)
//     		if($riqi != $now_riqi){
//     			//其他天统计之后加入数据库
//     			$res = Db::name('App_statistics')->insert($list);
//     		}
//     	}
		
    	
    	
    }
    /**
     * 今日零点到24点时间段
     * 数组形式返回
     */
    public function toDayTime(){
    	$start = strtotime(date('Y-m-d',time()));
    	$time[] = $start;
    	$time[] = $start+86400;
    	return $time;
    }
    public function getImformation($time){
    	//查询的日期
    	$riqi = date('Y-m-d',$time[0]);
    	//Y-m-d 格式时间
    	$ymd = $this->getYmdByTime($time);
    	//统计riqi这天的数据
    	$list['time'] = $riqi;
    	//收入充值TODO
    	// 			$list['get']
    	//提现TODO
    	// 			$list['give']
    	//新增会员
    	$map2['a.createTime'] = array('between',$time);
    	$map2['w.status'] = 1;
    	$list['num'] = Db::table('wst_users')->alias('a')
									 ->join('wst_app_member_relation w','a.userId = w.member_id')
			    					 ->where($map2)
			    					 ->count();
    	//会员总数
    	$map9['w.status'] = 1;
    	$list['all_num'] = Db::table('wst_users')->alias('a')
									 ->join('wst_app_member_relation w','a.userId = w.member_id')
			    					 ->where($map9)
			    					 ->count();
    	//新增业绩
    	$map3['finance_type'] = 1;
    	$map3['add_time'] = array('between',$time);
    	$map3['money'] = array('neq',50000);
    	$list['new_yeji'] = M('App_finance')->where($map3)->sum('money');
    	//总业绩
    	$map4['finance_type'] = 1;
    	$map4['money'] = array('neq',50000);
    	$list['all_yeji'] = M('App_finance')->where($map4)->sum('money');
    	//发放奖金
    	$jiang_arr = $this->getTypeArr();
    	$map5['finance_type'] = array('in',$jiang_arr);
    	$map5['add_time'] = array('between',$time);
    	$list['new_jiang'] = M('App_finance')->where($map5)->sum('money');
    	//总发放奖金
    	$map6['finance_type'] = array('in',$jiang_arr);
    	$list['all_jiang'] = M('App_finance')->where($map6)->sum('money');
    	//今日复投
    	$map7['finance_type'] = 15;
    	$map7['add_time'] = array('between',$time);
    	$list['new_futou'] = M('App_finance')->where($map7)->sum('money');
    	//总复投
    	$map8['finance_type'] = 15;
    	$list['all_futou'] = M('App_finance')->where($map8)->sum('money');
    	//今日拨比
    	$new_get = $list['new_yeji'] + $list['new_futou'];
    	if($new_get == 0){
    		$list['bobi'] = 0;
    	}else{
    		$list['bobi'] =  round($list['new_jiang']/$new_get*100,2);
    	}
    	
    	//总拨比
    	$all_get = $list['all_yeji'] + $list['all_futou'];
    	if($all_get == 0){
    		$list['all_bobi'] =0;
    	}else{
    		$list['all_bobi'] = round($list['all_jiang']/$all_get*100,2);
    	}
    	foreach($list as $k=>$v){
    		$list[$k] = $list[$k]?$list[$k]:'0';
    	}
    	return $list;
    }
    
    //获得奖励财务日志数组
    public function getTypeArr(){
    	//推荐奖
    	$arr[] = 7;
    	//层奖
    	$arr[] = 8;
    	//量奖
    	$arr[] = 9;
    	//管理奖
    	$arr[] = 10;
    	//股东分红
    	$arr[] = 11;
    	//激励分红
    	$arr[] = 12;
    	//报单中心奖
    	$arr[] = 13;
    	$arr[] = 14;
    	return $arr;
    }
    
    public function getYmdByTime($time){
    	$date[] = date('Y-m-d H:i:s',$time[0]);
    	$date[] = date('Y-m-d H:i:s',$time[1]);
    	return $date;
    }
    
}